package com.hzm.test.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    private Jackson2JsonRedisSerializer jsonRedisSerializer;

    @Bean
    public Jackson2JsonRedisSerializer jsonRedisSerializer() {

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化Redis的value值(默认使用JDK的序列化方式)
        jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();

        //指定要序列化的域,field,get和set,以及修饰符范围,ANY表示都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

        //指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jsonRedisSerializer.setObjectMapper(objectMapper);

        return jsonRedisSerializer;
    }

    @Bean()
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

       /* // KryoRedisSerializer 替换默认序列化
        KryoRedisSerializer kryoRedisSerializer = new KryoRedisSerializer(Object.class);
        redisTemplate.setValueSerializer(kryoRedisSerializer);
        redisTemplate.setKeySerializer(kryoRedisSerializer);
        redisTemplate.afterPropertiesSet();*/

        // StringRedisSerializer 进行序列化
        /*redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();*/


        //设置value的序列化规则和key的序列化规则
        redisTemplate.setValueSerializer(jsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jsonRedisSerializer);

        //使用StringRedisSerializer来序列化和反序列化Redis的key值
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        //设置hash key和value序列化模式
        redisTemplate.setHashKeySerializer(redisTemplate.getKeySerializer());
        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

}
